<?php

	// +----------------------------------------------------------------------
	// | 插件控制器
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\admin;

	use yicmf\addon\model\Addon as AddonModel;
	use yicmf\addon\Service;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use think\facade\Env;

	class Addon extends Common
	{
		/**
		 * @var Service
		 */
		protected $addon_event;

		protected function initialize()
		{
			parent::initialize();
			$this->addon_event =  app('addon');
		}

		public function _filter()
		{
			return [];
		}

		public function index()
		{
			// 显示页面
			$builder = new Table();
			$builder->model(AddonModel::class)
				->where($this->_filter())
				->order('id DESC')
				->setSearchPostUrl('', '')
				->suggest('插件路径：' . $this->addon_event->getPath())
				->searchText('title', '插件标题', '插件标题')
				->buttonRefresh('refresh', '刷新本地插件')
				->keyId()
				->keyTitle()
				->keyText('name', '标识')
				->keyText('version', '版本')
				->keyAuthor('author', '作者')
				->keyUpdateTime()
				->keyStatus([-1 => '禁用',
					0 => '未安装',
					1 => '已安装'])
				->actionUpdate('config?id={$id}', '配置', function ($data) {
					return 1 == $data['status'] && 1 == $data['has_config'];
				})
				->actionForbid('uninstall?name={$name}', '卸载', [-1, 1, 2])
				->actionToCheck('install?name={$name}', '安装', [0]);
			return $builder->fetch();
		}

		/**
		 * 刷新本地插件
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function refresh()
		{
			$result = $this->addon_event->refresh();
			if (0 == $result['code']) {
				$this->_returnSuccess( $result['message']);
			} else {
				$this->_returnError( $result['message']);
			}
		}

		/**
		 * 安装插件
		 */
		public function install()
		{
			$result = $this->addon_event->install($this->request->get('name'));
			if (0 == $result['code']) {
				$this->_returnSuccess( '安装成功');
			} else {
				$this->_returnError( $result['message']);
			}
		}

		/**
		 * 卸载插件.
		 */
		public function uninstall()
		{
			$result = $this->addon_event->uninstall(trim($this->request->get('name')));
			if (0 == $result['code']) {
				$this->_returnSuccess( '卸载成功');
			} else {
				$this->_returnError( $result['message']);
			}
		}

		/**
		 * 插件后台显示页面
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function lists()
		{
			$name = $this->request->param('_addon','');
			if (!$name)
			{
				$this->_returnError( '插件不存在');
			}
			$this->assign('name', $name);
			$class = get_addon_class($name);
			if (!class_exists($class)) {
				$this->_returnError( '插件不存在');
			}
			$addon = new $class();
			$this->assign('addon', $addon);
			if (!empty($addon->assign_list)) {
				$this->assign($addon->assign_list);
			}
			// 此处更新了显示逻辑，不再兼容旧版系统
			if ($addon->adminlist_file) {
				return $this->fetch($addon->addon_path . $addon->adminlist_file);
			} else {
				$classNamespace = get_addon_class($name, 'controller',$addon->admin_controller);
		 		if ($classNamespace) {
					$controllerObj = new $classNamespace();
					if ($controllerObj === false) {
						$this->_returnError( '插件初始化失败');
					}
					// 调用操作
					return call_user_func([
						$controllerObj,
						$addon->admin_action,
					]);
				} else {
					$this->_returnError( '插件必要文件缺失，请联系开发者');
				}
			}
		}

		/**
		 * 插件配置页面
		 * @return string
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function config()
		{
			if ($this->request->isPost()) {
				$addon_class = get_addon_class($this->request->post('addon_name'));
				if (!class_exists($addon_class)) {
					$this->_returnError( '插件' . $addon_class . '实例化失败', true);
				} else {
					$addon_obj = new $addon_class();
					$result = $addon_obj->setConfig($this->request->except('addon_name,user,v,m'));
					if (0 == $result['code']) {
						$this->_returnSuccess( $result['message'], true);
					} else {
						$this->_returnError( $result['message']);
					}
				}
			} else {
				// 支持插件自定义配置方法及默认的配置方法
				$addon = AddonModel::where('id', $this->request->param('id'))->where('status', 1)->find();
				if (!$addon) {
					$this->_returnError( '插件未安装');
				}
				$addon_class = get_addon_class($addon['name']);
				if (!class_exists($addon_class)) {
					$this->_returnError( "插件{$addon['name']}实例化失败");
				}
				$addon_obj = new $addon_class();
				$class = get_addon_class($addon['name'], 'controller',$addon_obj->admin_controller);

				if (class_exists($class) && method_exists(new $class(), $addon_obj->config_action)) {
					$controller_config = new $class();
					if ($controller_config === false) {
						$this->_returnError( '插件配置初始化失败');
					}
					// 调用操作
					return call_user_func([
						$controller_config,
						$addon_obj->config_action,
					]);
				} else {
					$config = $addon_obj->getBuilder();
					if (!empty($config)) {
						$builder = new Edit();
						$builder->title('插件【' . $addon['title'] . '】配置')->keys($config['keyList']);
						$builder->keyHidden('addon_name');
						if (isset($config['explaints'])) {
							$builder->explain($config['explaints']);
						}
						$builder->data(array_merge($addon_obj->getConfig(), ['addon_name' => $addon['name']]))
							->buttonSubmit();
						return $builder->fetch();
					} else {
						$this->_returnError( '当前插件不需要配置文件');
					}
				}
			}
		}
	}
